<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>增加删除一个元素</title>
		
		<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
		<style type="text/css">
			.container{
				border: 1px solid #AAA;
				overflow: hidden;
			}
			
			.block{
				float: left;
				margin: 10px;
				border: 1px solid #AAA;
				background-color: #FCC;
				width: 100px;
				height: 100px;
			}
			
			.block:hover{
				box-shadow: 8px 8px 8px #999;
			}
			
			.close{
				float: right;
				padding: 5px;
				font-weight: bold;
				opacity: 0.5;
				cursor: pointer;
			}
			
			.colse:hover{
				opacity: 1;
			}
		</style>
	
	</head>
	
	<body>
		<input type="button" class="btn" value="Add a block" />
		
		<div class="container">
			<!-- <div class="block">
				<span class="close">x</span>
			</div> -->
		</div>
		
		<script type="text/javascript">
			// 1. 找到按钮,绑定单击事件
			// 2. (创建一个新的div)添加一个新的矩形,颜色随机,灰色,然后append
			$(function(){
				var $div = $('.container');
				$('.btn').click(function(e){
					//加入多行html
					// jQuery创建新元素,用到多行字符串;
					// 	1.在除了最后一个以外,每行结尾加上反斜杠\
					// var $block = $('<div class="block">\
					// 					<span class="close">x</span>\
					// 				</div>')
					// 	2.用``包住多行字符串,ES6用法
					var $block = $(`<div class="block">\
										<span class="close">x</span>\
									</div>`)
					
					var r = g = b = parseInt(Math.random() * 256);
					
					$block.css('background-color','rgb(' + r + ',' + g + ','+ b +')');
					
					//但是这样做会产生大量的事件挂在DOM tree上
					// $block.find('.close').click(function(e){
					// 	$(e.target).parent().remove();
					// });
					
					$div.prepend($block);
					
				});
				
				$div.click(function(e){
					var $close = $(e.target);
					// is函数的使用,常用
					if($close.is('.close')){
						$close.parent().remove();
					}
					e.stopPropagation();
				});
				
			}); 
			
		</script>
	</body>
</html>
